import './public-path'
import React from 'react'
import ReactDOM, { Root } from 'react-dom/client'
import App from './App'
import { QiankunApp } from '@lhy-assist/qiankun'
import { qiankunApp } from './qiankun/qiankun-app'
import { PlatformFrameProps } from 'qiankun-frame'
import { appName } from '@/config'
import '@/asset/css/index.scss'

export class ReactApp {
  protected static app: Root | null = null

  public static render(container?: HTMLElement, activeRule?: string) {
    const app = (this.app = ReactDOM.createRoot(container || (document.getElementById('root') as HTMLElement)))
    app.render(
      <React.StrictMode>
        <App baseUrl={activeRule} />
      </React.StrictMode>
    )
  }

  public static destroy() {
    this.app?.unmount()
    this.app = null
  }
}

// 非qiankun子应用时独立启动app
if (!QiankunApp.qiankunEnvActive) {
  ReactApp.render()
}

// ************* 暴露钩子函数给qiankun ************* //
export async function bootstrap() {
  console.log(`${appName} bootstrap`)
}

export async function mount(props: PlatformFrameProps) {
  console.log(`${appName} mount`)
  qiankunApp.setFrame(props.frame)
  ReactApp.render(props.container, props.activeRule)
}

export async function unmount() {
  console.log(`${appName} unmount`)
  ReactApp.destroy()
}
